home *** CD-ROM | disk | FTP | other *** search
/ Info-Mac 4 / Info_Mac IV CD-ROM (Pacific HiTech Inc.)(August 1994).iso / Science / RLaB / examples / detrend.r < prev    next >
Text File  |  1994-04-25  |  737b  |  44 lines

  1. // detrend.r:
  2. //  Remove a linear trend from a vector.
  3. //  y = detrend(x) removes the best straight-line fit 
  4. //  from the data in vector x and returns it in vector y.
  5.  
  6. detrend = function(x) 
  7. {
  8.   local(a, b, m, q1, qra, r, x, y, z);
  9.  
  10.   m = max(size(x));
  11.   y = x;
  12.  
  13.   // Least Squares Solution
  14.  
  15.   a = [(1:m)./m; ones(1,m)]';
  16.   qra = qr(a);
  17.   q1 = qra.q[;1:size(a)[2]];
  18.   r = qra.r[1:size(a)[2];];
  19.  
  20.   z = y*q1;
  21.   b = solve(r, z');
  22.  
  23.   // Subtract out trend
  24.   y = y' - a*b;
  25.  
  26.   return y';
  27. };
  28.  
  29. //
  30. // Simple example using above function
  31. //
  32.  
  33.  t=0:100;
  34.  y = t + t .* sin(t/2);
  35.  ydt = detrend(y);
  36.  
  37.  plgrid ();
  38.  ptitle ( "RLaB Data Detrend Example" );
  39.  xlabel ( "Independent Variable" );
  40.  ylabel ( "Dependent Variable" );
  41.  
  42.  plot( [ [t;y;ydt]' ] );
  43.  
  44.